package com.hxq.wap.service;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;

import com.hxq.wap.dao.UserDao;
import com.hxq.wap.entity.UserEntity;

@Service("userService")
public class UserServiceImp implements UserService{
	//@Autowired是声明自动注入相应对象的注解，注入对象的类型须是接口类型
	@Autowired
	private UserDao dao;

	@Override
	public UserEntity login(String userName,String password) {
		return dao.findByUserNameAndPassword(userName, password);
	}

	@Override
	public void save(UserEntity userEntity) {
		dao.save(userEntity);
		
	}

	@Override
	public List<UserEntity> findSearch(final UserEntity model) {
		Assert.notNull(model);

		List<UserEntity> result=null;
		Specification<UserEntity> querySpecifi = new Specification<UserEntity>() {
	        @Override
	        public Predicate toPredicate(Root<UserEntity> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
	        	Predicate p1 = cb.like(root.get("userName").as(String.class), "%"+model.getUserName()+"%");  
	            Predicate p2 = cb.equal(root.get("password").as(String.class), model.getPassword());  
	            Predicate p3 = cb.gt(root.get("age").as(Integer.class), model.getAge());  //gt 大于
	            //把Predicate应用到CriteriaQuery中去,因为还可以给CriteriaQuery添加其他的功能，比如排序、分组啥的  
	            query.where(cb.and(p3,cb.or(p1,p2)));  
	            //添加排序的功能  
	            query.orderBy(cb.desc(root.get("id").as(Integer.class)));  
	              
	            return query.getRestriction(); 
	        }

	    };
	    result = dao.findAll(querySpecifi);
	    return result;
	}

	@Override
	public void updatePassword(String userName, String password) {
		dao.updatePassword(userName, password);
		
	}

	@Override
	public int deleteByEgId(int id) {
		dao.deleteByEgId(id);
		return 0;
	}

	@Override
	public Long countByUserName(String userName) {
		
		return dao.countByUserName(userName);
	}

	@Override
	public List<UserEntity> findAll(Sort sort) {
		return dao.findAll(sort);
	}

	@Override
	public Page<UserEntity> findAll(Pageable pageable) {
		
		return dao.findAll(pageable);
	}

	@Override
	public List<UserEntity> findAll(Specification<UserEntity> buildSpecification) {
		
		return dao.findAll(buildSpecification);
	}





}
